package com.strato.rule.jdbc.v1_0_0;

import java.util.Date;

import com.strato.annotation.osgi.v1_0_0.service.OsgiService;
import com.strato.jdbc.datasource.v1_0_0.DataSourceFactory;
import com.strato.mvc.api.v1_0_0.user.UserContext;
import com.strato.orm.mybatis.v1_0_0.annotation.MybatisWired;
import com.strato.rule.core.v1_0_0.execution.RuleSet;
import com.strato.rule.core.v1_0_0.storage.RuleSetStore;
import com.strato.rule.jdbc.v1_0_0.dao.mapper.RuleSetMapper;
import com.strato.saas.merchant.v1_0_0.MerchantContextHolder;

@OsgiService
public class RuleSetJdbcStore implements RuleSetStore {

	@MybatisWired(datasource=DataSourceFactory.MERCHANT_DATASOURCE)
	RuleSetMapper ruleSetMapper;
	@Override
	public void save(RuleSet ruleSet) {
		String ruleSetId=ruleSet.getId();
		String merchantId=MerchantContextHolder.get();
		String userId=UserContext.get();
		com.strato.rule.jdbc.v1_0_0.model.RuleSet old = ruleSetMapper.selectByPrimaryKey(ruleSetId);
		String content=ruleSet.toString();
		com.strato.rule.jdbc.v1_0_0.model.RuleSet record=new com.strato.rule.jdbc.v1_0_0.model.RuleSet();
		record.setRuleSetId(ruleSetId);
		record.setMerchantId(merchantId);
		record.setRuleContent(content);
		Date now=new Date();
		record.setUpdatedBy(userId);
		record.setUpdatedDate(now);
		if(old==null){
			record.setCreatedBy(userId);
			record.setCreatedDate(new Date());
			ruleSetMapper.insert(record);
		}else{
			ruleSetMapper.updateByPrimaryKeySelective(record);
		}
		
	}
	

	@Override
	public RuleSet load(String ruleSetId) {
		com.strato.rule.jdbc.v1_0_0.model.RuleSet record=ruleSetMapper.selectByPrimaryKey(ruleSetId);
		if(record==null){
			return null;
		}
		String content=record.getRuleContent();
		RuleSet ruleSet = RuleSet.fromString(content);
		return ruleSet;
	}


	@Override
	public void delete(String ruleSetId) {
		ruleSetMapper.deleteByPrimaryKey(ruleSetId);
	}

}
